
/*
*Pool Public Licence version 0.1 or later
*Released on 20th April 2008.
*Any voilations can be repoted at paritosh@wikiocean.net
*What is treated as voilations can be found at www.wikiocean.net/ppl1-voilations* 
******************************************************************************
* The contents of this file are subject Affero GPL v3 and later with additional conditions.
* The additional conditions are to be considered as part of the Affero GPL v3 and later.
* The additional conditions will supersede the Affero GPLv3 and later in case of conflict.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the License at http://www.gnu.org/licenses/agpl.html
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya.
* created by Paritosh Pungaliya are Copyright (C) Paritosh Pungaliya; All Rights Reserved.
* Contributions are Copyright (C) 2001-2008 Paritosh Pungaliya.

* Objective of the additional terms (license) 
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencie(s).
* 3) To avoid a situation where big corporates or investors can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the openness changes in companies that get Venture Capital funding.)
* (if you agree to this logic I invite you to our group to work together)

* Additional conditions
*  0) Source code will also include
* 	a) data dictionaries, data ontologies which are used to alter the behavior of code or to control           the features of application.
* 	b) Any code generated or derived automatically or manually from this code or logic
*  1) The revenue generated by deploying, implementing , selling services and other activities
*  	 based on this source code should be shared 100%, between the people working on it.
*  2) Capital invested should be given only fixed rate of return or linked to revenue/surplus growth for limited time.
*  3) People working on the project should always have an option to replace the capital provider in full or part with lower cost capital.
*  4) Their should not be any ownership which can be sold as a claim on future profit to be generated from the work of people working on the code.
*  5) Brand thus generated should belong to the group.
*  6) For old and new members revenue sharing should be equal for same work equivalent.
*  7) The share of revenue should be decided by bidding for work before allocation of work within the group.
*  8) Before bidding various method of measuring the work should be clearly defined and published in public domain. Any change in process should also be publised in public domain imediately.
*  9) All data related to to revenue sharing should be published as and when generated in public domain.
*  10) For group of people having size more than 10 people will have to make it open online for others to participate in bids. 
*  11) All people involved in related and sub project will be treated as a group.
*  12) Once this license is being used for a certain code then all and any other software services being provided by the group should complusorilly come under 100% revenue sharing.
*  13) Cross subsidization should not happen under this revenue share, no additional benefit should be drawn from the people, by the employing agency.
*  14) Any position or knowledge or legal structure created relating to people working on code, which adversely affects the spirit of 100% revenue share will be treated as a violation.
*  15) Revenue sharing defined.
*     a) includes direct revenue and also intangible gains like brand, and organization.
*     b) No personal judgment should be involved in judging the distribution of revenue.It has to be pre-defined formula based.
*     c)100% of revenue should be shared before expenses and recievers should have control over what expenses to incur.
*     d)For the work done in any month by contributing group member, working on any project can be given revenue share from the work done by the group, for a maximum of 18 months after that month.
*     e)Revenue should be apportioned to the month in which work is done and not when received.
*  The group fulfilling the above conditions also has to be a wiki ecosystem further defined in www.wekosystem.org or read about Wekosystem at www.wikiocean.net

*  ******************************************************************************
*/  
package pool.tablename;

import java.sql.ResultSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;

import pool.bean.IdBean;
import pool.tablename.Property_details;
//import basicprocess.Basicprocess;

import timer.ExecutionTimer;
import timer.TimerRecordFile;
import utility.ConvertToLower;

import utility.MessageGenerator;
import database.RecordSearch;
import dbmanager.ChekInMaster;
import dbmanager.Column;




/**
 * @author Master_table class.
 * */

public class  Master_table extends SubPool 
{
	
	//private String pl_tableName= "property_details"; /** Contains TableName property_details.*/
	//MasterBasicReports mbs;
	
	private String tableName = "master_table"; /** Contains master_table name*/
	private String TYPE="type"; /** Contains type like Employee or Item, etc. from Command sent through Mobile.*/	
	
	public Hashtable<Object,Object> BasicMasterMap = new Hashtable<Object,Object>(); /** Contains master request Hash Command from request.*/
	public Hashtable<Object,Object> MasterMap = new Hashtable<Object,Object>(); /** Contains master request Hash Command from request.*/
	
	public Property_details pd; /**Creating reference variable of Property_details.*/		
	
	
	private Hashtable<Object,Object> oldMasterMap = new Hashtable<Object, Object>(); /** It will get stores old message for Update.*/
	private Hashtable<Object,Object> newMasterMap = new Hashtable<Object,Object>(); /** It will get stores new message for Update.*/
	
	private Hashtable<Object,Object> ViewHashtable = new Hashtable<Object, Object>();
	
	
	/**Default constructor of Master_table class.*/	
	public Master_table() {}
	
			
	/** The getInsert() will insert the word into the master_table table.
	 *  @return sbrDTB, StringBuffer which store the insertion message for the logger class.
	 * */	
	
	@SuppressWarnings("unchecked")
	public StringBuffer getInsert()
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		TYPE=gin.getId(TYPE);

		/*-----------------------------------------------------------------*/
		
		Vector<Object> basicReportVector = new Vector<Object>();
		System.out.println("pool::MasterClass::getInsert()::You are in getInsert of master");
		String id=null;
		Hashtable<Object, Object> Error = new Hashtable<Object, Object>();
		Error.putAll(process());
		if(Error.containsKey("ErrorInput"))
		{
			return new StringBuffer(Error.toString());
		}
		IdBean maxId = new IdBean(sqlDB);
		maxId.setTable(Request);
		maxId.execute();
		id = maxId.getId();
		
		MasterMap.put("id", id); //ADD THE ID TO MASTERMAP HASH
		System.out.println("pool::MasterClass::getInsert()::MasterMap -->> "+MasterMap);
		
		ChekInMaster check = new ChekInMaster(sqlDB);
		
		/*---------------------------------------------------------------------*/		
		/** Check for Name is present in Master_Table, if 'No' then it will get insertesd in to master_table.
		  * Otherwise Displays message "Already Present in Master".
		  * */
		if ( MasterMap.get("name").equals("") == false)
		{
			if(check.isInMaster(MasterMap.get("name").toString())== false) 
			{
							
				int resInsert = sqlDB.getInsert(Request, MasterMap); /** Stores result from master, "1" for successfully insertion otherwise "0".*/
				if(resInsert > 0)
				{
					
					flagResult = true;
					
					System.out.println(MasterMap.get("name")+" pool::MasterClass::getInsert():: Inserted in Master_table Success fully......\n\n");

					/** UPDATE THE max_id_table TABLE VALUES. */
					
					maxId.update();
					
					//It will make a call to Constructor of the MasterBasicReports.
					//mbs = new MasterBasicReports(id,Request,sqlDB,process);
					//mbs.insertReport(); // It will make a call to insert() method of the MasterBasicReports.
					
					basicReportVector.add(MasterMap);
					
					pd.mid = id; // Here, we are setting the mid for the property_details table.
					pd.flagResult = flagResult;
					
					sbrDTB.append("Following Object is inserted :"+MasterMap.get("name"));
					sbrDTB.append(pd.getInsert()); // It will get call the insert() method of property_details class.
					
					strID = id;		
					
					flagResult = pd.boolPdSetCommit;
									
				}
				else
				{
					System.out.println("pool::MasterClass::getInsert():: Please Insert again....\n\n");
					sbrDTB.append("Error :: Please Insert again....\n\n");
				
					flagResult = false;
				}				
				
			}
			else
			{
				System.out.println("\n pool::MasterClass::getInsert()::  "+MasterMap.get("name")+"  Already Present in Master, so please insert another new word....\n");
				sbrDTB.append("\n Error: "+MasterMap.get("name")+" Already Present in Master, so please insert another new word....\n");
			
				flagResult = false;
			}
		}
		else
		{
			System.out.println(" pool::MasterClass::getInsert():: No master name is present in request....\n\n");
			sbrDTB.append("Error : Master name is not available in request....\n\n");
			
			flagResult = false;
		}
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Master_table","getInsert",t.duration());
		return sbrDTB.append("\n");
	}
	
	
	public StringBuffer getUpdate()
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();

		try
		{	
			ResultSet rs; /**Creating reference variable of Result set.*/			
			
			ChekInMaster check = new ChekInMaster(sqlDB);
			
			/** Check for Name is present in Master_Table, if 'YES' then it will get update in to master_table.
			  * Otherwise make a call to getInsert() method of master_table.
			  * */
				if(check.isInMaster(oldMasterMap.get("name").toString())== true) 
				{
					if(check.isInMaster(newMasterMap.get("name").toString()) == true)
					{
						System.out.println(" pool::MasterClass::getUpdate():: " + newMasterMap.get("name") + " Unalbe to update, Because entry in master_table already exists.....");
						sqlDB.pLog.Logger.append(" pool::MasterClass::getUpdate():: " + newMasterMap.get("name") + "Unalbe to update, Because entry in master_table already exists.....");
						sbrDTB.append( " pool::MasterClass::getUpdate():: " + newMasterMap.get("name") + "Unalbe to update, Because entry in master_table already exists.....");
					
						flagResult = false;					
					}
					else
					{
						String id=null;
						try
						{
							rs = sqlDB.getSelect("select id from master_table where name = '"+oldMasterMap.get("name").toString()+"'");
							rs.next();
							id = rs.getString("id");
							rs.close();
						}
						catch (Exception e)
						{
							e.printStackTrace();
						}				
						
						oldMasterMap.put("id", id); //ADD ID TO THE OLDMASTERMAP HASH						
						newMasterMap.put("id", id);  //ADD ID TO THE NEWMASTERMAP HASH							
						
						System.out.println("pool::MasterClass::getUpdate()::oldMasterMap -->> " + oldMasterMap);
						System.out.println("pool::MasterClass::getUpdate()::newMasterMap -->> " + newMasterMap);
						sqlDB.setBeforeCommit();						
						int j = sqlDB.getUpdate(Request,newMasterMap,oldMasterMap);
						if(j>0)
						{		
							
							//sqlDB.setCommit(true);
							
							System.out.println(" pool::MasterClass::getUpdate():: "+oldMasterMap.get("name") + " updated Success fully with " + newMasterMap.get("name"));
							sbrDTB.append( "Following master is updated : "+newMasterMap.toString());
							sqlDB.pLog.Logger.append(" pool::MasterClass::getUpdate():: "+oldMasterMap.get("name") + " updated Success fully with " + newMasterMap.get("name"));
							
							strID = id;
							flagResult = true;						
						}
						else
						{
							System.out.println(" pool::MasterClass::getUpdate():: " + oldMasterMap.get("name") + " Unalbe to update.....");
							sqlDB.pLog.Logger.append(" pool::MasterClass::getUpdate():: " + oldMasterMap.get("name") + " Unalbe to update.....");
						
							flagResult = false;
						}
					}
				}
				else
				{
					System.out.println(" pool::MasterClass::getUpdate():: " + newMasterMap.get("name") + " Unalbe to update, Because entry in master_table already exists.....");
					sbrDTB.append( " pool::MasterClass::getUpdate():: " + newMasterMap.get("name") + "Unalbe to update, Because entry in master_table already exists.....");
					sqlDB.pLog.Logger.append(" pool::MasterClass::getUpdate():: " + newMasterMap.get("name") + "Unalbe to update, Because entry in master_table already exists.....");
				
					flagResult = false;
				}			
		}		
		catch (Exception e) 
		{
			System.out.println("pool::MasterClass::getUpdate():: Exception :: Enter Valid message for update");
			e.printStackTrace();			
		}
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Master_table","getUpdate",t.duration());
		return sbrDTB;
	}

	
	public StringBuffer getView() 
	{
		ExecutionTimer t = new ExecutionTimer();
		t.start();		 
		
		StringBuffer sbrProperty=new StringBuffer();
		 
	//	Hashtable<Object,Object> MasterMap = new Hashtable<Object,Object>();
		String mastermsg="";
		 
		//MasterMap.putAll(ViewHashtable);
		//MasterMap = gin.getHashMapOfValues(MasterMap);
		//MessageGenerator msg=new MessageGenerator(sqlDB);
		//mastermsg=msg.MasterMessage(tableName, MasterMap, process);
	/*	if(mastermsg.equals(""))
		{
			sbrProperty.append("Check master spchar or  master-name ");
			return sbrProperty;
		}*/
		
		sbrProperty.append(mastermsg);
		MasterMap.putAll(ConvertToLower.convertHashKey(MasterMap));
		
		pd.setMasterMap(MasterMap);
		//public ReplacesSpecialCharacter replace;	
		//public final String BASIC_MASTER_REPORT_PATH = Input.MASTERREPORTSPATH ;
		//public final String BASIC_TRANSACTION_REPORT_PATH = Input.TRASACTIONREPORTSPATH;   
		//public Hashtable<Object, Object> hashMap = new Hashtable<Object, Object>();
		//public abstract Hashtable<Object, Object> initialize();	
		//Vector<Object> newVector;
		//Vector<Object> oldVector;
		//private 	
		//

	
		sbrProperty.append(pd.getView());
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Master_table","getView",t.duration());
		return sbrProperty;
	
	}
	
	
	
	public String getType() 
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		String MasterType;
		MasterType = "null";
		
		try 
		{	
			Hashtable<Object,Object> temp = new Hashtable<Object,Object>();
			for(int i=0;i<pd.PropertyList.size();i++)
			{
				temp.clear();
				Property_details pd1 = (Property_details)pd.PropertyList.get(i);
				temp.putAll((Hashtable<Object, Object>)  ConvertToLower.convertHashKey(pd1.PropertyMap));
				String pidvalue = temp.get("pid").toString();
				if(pidvalue.toLowerCase().equals(TYPE))
				{
					MasterType = temp.get("pv").toString();
					type = MasterType;
					return MasterType;
				}
			}
			if(MasterType.equals("null"))
			{
				String id =MasterMap.get("name").toString();
				id = gin.getId(id);
				//String path = Input.MASTERREPORTSPATH + id + "//" + id + "_mid" +Input.FILRFORMAT;
				temp.clear();
				temp.put("pid",TYPE);
				temp.put("mid", id);
				temp.put("td", "null");
				/*SearchRecord sr = new SearchRecord(path);
				String line[] =sr.getRecordSet(temp);*/
				RecordSearch ps = new RecordSearch(sqlDB);
				ps.setConditionMap(temp);
				String line[] = ps.getArrayFromResultSet();
				for(int i=0;i<line.length;i++)
				{
					String Splitline[]= line[i].split("\t");
					try 
					{
							MasterType = Splitline[Column.pv_index-1];
					} 
					catch (Exception e) {
						type = MasterType = Splitline[Column.pv_index-1];
					}
				}
			}
			if(MasterType.equals("null"))
				type=MasterType = pd.getType();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Master_table","getType",t.duration());
	  return MasterType; 	

	}
	
	
	public Hashtable<Object, Object> getBasicHashtable() {
		return BasicMasterMap;
	}


	public void setHashtable(Hashtable<Object, Object> table)
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		MasterMap.putAll(table);
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Master_table","setHashtable",t.duration());
		
	}
	
	public void setPropertyVector(Vector<Object> propertydetails) 
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		pd.PropertyList = propertydetails;
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Master_table","setPropertyVector",t.duration());
	}
	

	public void setOldHashtable(Hashtable<Object, Object> table)
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		oldMasterMap.putAll(table);
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Master_table","setOldHashtable",t.duration());
		
	}
	public void setNewHashtable(Hashtable<Object, Object> table)
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		newMasterMap.putAll(table);
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Master_table","setNewHashtable",t.duration());
		
	}
	
	
	public void setViewHashtable(Hashtable<Object,Object> hashtable) {
		ViewHashtable.putAll(hashtable);
	}
	
	
	public void setPropertyViewHashtable(Hashtable<Object,Object> hashtable) {
		pd.ViewHashtable.putAll(hashtable);
	}
	
	public StringBuffer getDelete()
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		TYPE=gin.getId(TYPE);	
		
		Vector<Object> basicReportVector = new Vector<Object>();
		System.out.println("pool::MasterClass::getInsert()::You are in getInsert of master");
		String id=null;
		Hashtable<Object, Object> Error = new Hashtable<Object, Object>();
		Error.putAll(process());
		if(Error.containsKey("ErrorInput"))
		{
			return new StringBuffer(Error.toString());
		}
		id= gin.getId(MasterMap.get("name").toString());
		if(!id.equals("no$"))
		{
			MasterMap.put("id", id); //ADD THE ID TO MASTERMAP HASH
			System.out.println("pool::MasterClass::getInsert()::MasterMap -->> "+MasterMap);
			
			ChekInMaster check = new ChekInMaster(sqlDB);
			
			/*---------------------------------------------------------------------*/		
			/** Check for Name is present in Master_Table, if 'No' then it will get insertesd in to master_table.
			  * Otherwise Displays message "Already Present in Master".
			  * */
			if ( MasterMap.get("name").equals("") == false)
			{
				if(check.isInMaster(MasterMap.get("name").toString())== true) 
				{				
					//int resInsert = sqlDB.getInsert(Request, MasterMap); /** Stores result from master, "1" for successfully insertion otherwise "0".*/
						
						flagResult = true;
						
						System.out.println(MasterMap.get("name")+" pool::MasterClass::getInsert():: Inserted in Master_table Success fully......\n\n");
	
						/** UPDATE THE max_id_table TABLE VALUES. */
						
					
						
						pd.mid = id; // Here, we are setting the mid for the property_details table.
						pd.flagResult = flagResult;
						
						//get all property of master
						
						RecordSearch rs =new RecordSearch(sqlDB);
						Hashtable<Object, Object> Condition =new Hashtable<Object, Object>();
						Condition.put("mid", id);
						Condition.put("td", "null");
						rs.setConditionMap(Condition);
						Vector<Object> property = rs.getVectorFromResultSet();
						for(int i=0;i<property.size();i++)
						{
							Condition.clear();
							Condition.putAll((Map<? extends Object, ? extends Object>) property.get(i));
							Property_details temppd= new Property_details(sqlDB);
							temppd.PropertyMap.putAll(Condition);
							pd.PropertyList.add(temppd);
						}
						sbrDTB.append("Following Object is inserted :"+MasterMap.get("name"));
						sbrDTB.append(pd.getDelete()); // It will get call the insert() method of property_details class.
						
						strID = id;		
						
						flagResult = pd.boolPdSetCommit;
					
				}
				else
				{
					System.out.println("\n pool::MasterClass::getInsert()::  "+MasterMap.get("name")+"  Already Present in Master, so please insert another new word....\n");
					sbrDTB.append("\n Error: "+MasterMap.get("name")+" Already Present in Master, so please insert another new word....\n");
				
					flagResult = false;
				}
			}
			else
			{
				System.out.println(" pool::MasterClass::getInsert():: No master name is present in request....\n\n");
				sbrDTB.append("Error : Master name is not available in request....\n\n");
				
				flagResult = false;
			}
		}	
		else
		{
			System.out.println(" pool::MasterClass::getInsert():: No master name is present in request....\n\n");
			sbrDTB.append("Error : Master name is not available in request....\n\n");
			
			flagResult = false;
		}
		t.end();
		@SuppressWarnings("unused")
		TimerRecordFile timerFile=new TimerRecordFile("pool.tablename","Master_table","getInsert",t.duration());
		return sbrDTB.append("\n");
	
	}	
	
	

	public Hashtable<Object, Object> getHashtabel() 
	{
		return MasterMap;
	}

	public Vector<Object> getpropertyVector() 
	{
		return pd.PropertyList;
	}


	public String getTable() 
	{
		return Request;
	}

	public Hashtable<Object, Object> getDetailHashtabel() 
	{	
		return new Hashtable<Object, Object>();
	}

}
